<template>
	<view class="container">
		<view class="form-section">
			<view class="form-group">
				<view class="section-title">审批流程记录</view>
        <view>
          <scroll-view  class="message-list" id="message-scroll" scroll-x="true" enable-flex="true" enhanced="true" >
            <u-steps :current="processActive">
              <u-steps-item v-for="(log, index) in taskLog" :key="index"  class="message-item">
                <template #content>
                  <view>
                    <text class="slot-title">
                      {{ log.taskName }}
                    </text>
                    <text class="slot-desc">
                      {{ log.taskOwnerName }} {{ log.actionName }}
                    </text>
                  </view>
                </template>
              </u-steps-item>
            </u-steps>
            </scroll-view>
        </view>
			</view>

			<view class="action-buttons">
        <u-button  @click="onClick('Back')" >
          <text class="bh-btu">驳回</text>
        </u-button>

				<u-button  type="primary"  @click="onClick('Pass')" >
          <text class="ty-btu">同意</text>
        </u-button>
			</view>
		</view>
	</view>

	<!-- 审批弹窗 -->
	<u-modal :show="showApproveModal" title="审批处理" :closeOnClickOverlay="true" :showCancelButton="true"
		@confirm="handleConfirm" @cancel="showApproveModal = false">
		<u-form :model="approveForm" :rules="approveRules" ref="approveFormRef">
			<u-form-item label="审批意见" prop="comment">
				<u-input v-model="approveForm.comment" type="textarea" placeholder="请输入审批意见" border="surround" />
			</u-form-item>
			<u-form-item label="下个环节">
				<u-input v-model="approveForm.nextDefinitionName" type="textarea" placeholder="暂无数据" disabled />
			</u-form-item>
			<u-form-item label="办理人" prop="nextAssignee">
				<u-input v-model="approveForm.nextAssignee" disabled type="textarea" placeholder="暂无数据" />
			</u-form-item>
		</u-form>
	</u-modal>

</template>

<script>
	export default {

		data() {
			return {
				taskInfo: {
          id: "",
          sourceId: "",
				},
				processFilter: { //审批记录查询条件
					bizInstId: null,
					procInstId: "",
					includeHistory: false,
					includeRetrieve: false,
					onlyIncludeCurrentProcInst: false,
					includeAdminOperate: false,
					isAdminOperateView: false
				},
				taskLog: [], //流程审批记录
				processActive: 0, //// 当前步骤索引
				showApproveModal: false, // 控制弹窗显示
				approveForm: {
					comment: '', // 审批意见
					nextDefinitionName: '', //下个环节名称
					nextAssignee: '', // 下个环节办理人
				},
				approveType: "",
				approveRules: {
					comment: {
						type: 'string',
						required: true,
						message: '请填写审批意见',
						trigger: ['blur', 'change']
					},
					nextAssignee: {
						type: 'string',
						required: false,
						message: '请选择下一个办理人',
						trigger: ['blur', 'change']
					}
				},
				assigneeList: [], //下个环节可选择办理人员
				//过滤参数
				taskfilter: {
					"owner": this.$commonUnits.getUserId(),
					"searchList": [],
					"stateList": [
						1,
						2
					],
					"pageable": true,
					"pageIndex": 0,
					"pageSize": 20,
					"categoryIdList": [], //流程类别id集合
					"onlyIncludeApprovalTask": true,
					"onlyIncludeReadTask": false
				},
				apikey: "48ddc0b3-cbc4-2f33-004f-6c02cdb00c83",
				currentTab: 0,
			};
		},

		onLoad(e) {
      this.taskInfo.id = e.id
      this.taskInfo.sourceId = e.sourceId
			this.processFilter.procInstId = e.processInstanceId
			this.getProcessLog();
		},

		methods: {
			getProcessLog() {
        this.$commonUnits.request(
            "runtime/task/v1.0/comment/list", "POST", this.processFilter,
            this.apikey
        ).then(res =>{
          this.taskLog = [];
          if (res.statusCode !== 200) {
            uni.showToast({
              title: '暂无数据',
              icon: 'none'
            });
            return;
          }
          // 数据处理
          const result = res.data
          result.some(log => {
            this.taskLog.push(log)
            if (log.actionName === null || log.action === 'End'){
              log.operatorName = '';
              log.actionName = '等待审批'
              if (log.action === 'End'){
                log.actionName = '流程结束'
              }
              return true;
            }
            return false;
          })
          this.processActive = this.taskLog.length - 1; // 默认选中最后一步

          // 跳转到最末尾
          uni.createSelectorQuery()
              .select('#message-scroll')
              .node()
              .exec((res) => {
                const scrollView = res[0].node;
                scrollView.scrollTo({left:99999});
              })


        })
            .catch((err) => {
              this.taskLog = {};
              uni.showToast({
                title: '获取审批日志失败，请重试',
                icon: 'none'
              });
            })

			},

      onClick(type) {
					uni.showLoading({
						title: '加载中...',
						mask: true // 防止用户点击
					});

					// 获取下一环节信息
					 this.$commonUnits.request(
						`runtime/wf/v1.0/workItems/complete-simulation`,
						"POST", {
							workItemId: this.taskInfo.sourceId, //任务信息sourceId
							conclusionValue: type // 审批类型  Pass/Reject
						},
						this.apikey
					).then(res=>{
             if (res.statusCode === 200) {
               if (type === 'Pass'){
                 this.approveForm.comment = '同意'
               }else {
                 this.approveForm.comment = '不同意'
               }
               this.approveForm.nextDefinitionName = res.data.simulationPaths[0].nodeInfoList[0].activityDefinitionName
               let assigneeList = []
               if (res.data.needInteraction) { //是否需要选择下个办理人
                 assigneeList = res.data.simulationPaths[0].nodeInfoList[0].assigneeInfo.assigneeUsers
               } else {
                 assigneeList = res.data.simulationPaths[0].nodeInfoList[0].selectedAssignees
               }
               this.approveForm.nextAssignee = assigneeList.map(assignee => assignee.name).join(", ");
               this.showApproveModal = true;
               this.approveType = type
             } else {
               uni.showToast({
                 title: '获取环节信息失败',
                 icon: 'none'
               });
             }
             uni.hideLoading();

           });
			},

			handleConfirm() {
        this.$refs.approveFormRef.validate()
            .then(res=>{
              if (res === true){
                this.completeTask()
              }else {
                uni.showToast({
                  title: res,
                  icon: 'none'
                });
              }
            });
			},

      completeTask(){
        uni.showLoading({
          title: '提交中...',
          mask: true
        });
        const approveData = {
          workItemId: this.taskInfo.sourceId,
          conclusionValue: this.approveType,
          comment: this.approveForm.comment,
        }
        this.$commonUnits.request(
            "runtime/wf/v1.0/workItems/complete",
            "POST",
            approveData,
            this.apikey
        ).then(res=>{

          if (res.statusCode === 200) {
            uni.showToast({
              title: '同意审批成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '审批失败' + res.Messsage,
              icon: 'none'
            });
          }

          uni.hideLoading();
          this.showApproveModal = false;
          this.getProcessLog();
        })
      }

		}
	};
</script>

<style lang="scss" >
	.container {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.form-section {
		padding: 20rpx;
	}

	.form-group {
		background: #ffffff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
    height: 180rpx;
	}

	.form-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 20rpx;
		border-left: 4rpx solid #1890ff;
		padding-left: 12rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 16rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	/* 标题区域 */
	.section-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 20rpx;
		border-left: 4rpx solid #1890ff;
		padding-left: 12rpx;
	}

	/* 审批记录 */
	.message-list {
    white-space: nowrap;
    flex-direction: row;
    -webkit-overflow-scrolling: touch;
    overflow-x: auto;
    width: 100%;
	}

  .u-steps {
    display: inline-flex !important;
    flex-wrap: nowrap !important;
  }

  .message-item {
    width: auto;
    text-align: center;
    min-width: 200rpx;
    flex-shrink: 0;
  }

	.slot-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	.slot-desc {
		font-size: 24rpx;
		color: #666;
		display: block;
	}

  .action-buttons{
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    text-align: center;
    display: flex;
  }

.bh-btu{
  font-size: 34rpx;
  color: #3A43B7;
}

.ty-btu{
  font-size: 34rpx;
  color: rgb(255, 255, 255);
}

</style>